package cn.exrick.manager.controller;


import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.ExportExcel;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.dto.OrderChartData;
import cn.exrick.manager.dto.OrderDetail;
import cn.exrick.manager.dto.OrderRanking;
import cn.exrick.manager.pojo.TbOrder;
import cn.exrick.manager.pojo.TbOrganization;
import cn.exrick.manager.pojo.TbUser;
import cn.exrick.manager.service.OrderService;
import cn.exrick.manager.service.OrganizationService;
import cn.exrick.manager.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@Api(description= "订单管理")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;

    @RequestMapping(value = "/order/list",method = RequestMethod.GET)
    @ApiOperation(value = "获取订单列表")
    public DataTablesResult getOrderList(int draw, int start, int length, TbOrder tbOrder,
                                         @RequestParam("order[0][column]") int orderCol, @RequestParam("order[0][dir]") String orderDir){

        //获取客户端需要排序的列
        String[] cols = {"checkbox","o.order_no", "o.create_time","o.user_id", "o.total_amount", "o.payment", "o.status"};
        String orderColumn = cols[orderCol];
        //默认排序列
        if(orderColumn == null) {
            orderColumn = "o.create_time";
        }
        //获取排序方式 默认为desc(asc)
        if(orderDir == null) {
            orderDir = "desc";
        }


        TbUser user = getCurrentUser();
        //部门负责人只能查看部门下的订单
        if(user.getRoleId() == CommonConstant.ROLE_ORG_CHARGE){
            List<String> organizationIds = organizationService.getChildOrganizationIds(user.getOrganizationId());
            tbOrder.setOrganizationIds(organizationIds);
        }
        DataTablesResult result= orderService.getOrderList(draw,start,length,tbOrder,orderColumn,orderDir);
        return result;
    }

    private TbUser getCurrentUser(){
        Subject subject = SecurityUtils.getSubject();
        String username = (String)subject.getPrincipal();
        return userService.getUserByUsername(username);
    }

    @RequestMapping(value = "/order/count",method = RequestMethod.GET)
    @ApiOperation(value = "获取订单总数")
    public Result<Object> getOrderCount(){
        TbOrder tbOrder = new TbOrder();
        TbUser user = getCurrentUser();
        //部门负责人只能查看部门下的订单
        if(user.getRoleId() == CommonConstant.ROLE_ORG_CHARGE){
            List<String> organizationIds = organizationService.getChildOrganizationIds(user.getOrganizationId());
            tbOrder.setOrganizationIds(organizationIds);
        }
        Long result=orderService.countOrder(tbOrder);
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/order/detail/{orderId}",method = RequestMethod.GET)
    @ApiOperation(value = "获取订单详情")
    public Result<Object> getOrderDetail(@PathVariable String orderId){

        OrderDetail orderDetail=orderService.getOrderDetail(orderId);
        return new ResultUtil<Object>().setData(orderDetail);
    }

    @RequestMapping(value = "/order/remark",method = RequestMethod.POST)
    @ApiOperation(value = "订单备注")
    public Result<Object> remark(@RequestParam String orderId,
                                 @RequestParam(required = false) String remark){

        orderService.remark(orderId,remark);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/order/deliver",method = RequestMethod.POST)
    @ApiOperation(value = "订单发货")
    public Result<Object> deliver(String orderId, String code,String status){
        TbOrder tbOrder = orderService.getTbOrderById(orderId);
        if(!code.equals(tbOrder.getCode())){
            return new ResultUtil<>().setErrorMsg("取货码不正确！");
        }

        orderService.deliver(orderId,status);
        return new ResultUtil<>().setData(null);
    }

    @RequestMapping(value = "/order/setPickingDays",method = RequestMethod.POST)
    @ApiOperation(value = "设置配货时间")
    public Result<Object> setPickingDays(String orderId, Integer pickingDays){
        orderService.updatePickingDays(orderId,pickingDays);
        return new ResultUtil<>().setData(null);
    }

    @RequestMapping(value = "/order/cancel/{orderId}",method = RequestMethod.GET)
    @ApiOperation(value = "订单取消")
    public Result<Object> cancelOrderByAdmin(@PathVariable String orderId){

        orderService.cancelOrderByAdmin(orderId);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/order/invalid/{orderId}",method = RequestMethod.GET)
    @ApiOperation(value = "订单无效")
    public Result<Object> invalidOrder(@PathVariable String orderId){

        orderService.invalidOrder(orderId);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/order/del/{ids}",method = RequestMethod.DELETE)
    @ApiOperation(value = "删除订单")
    public Result<Object> getUserInfo(@PathVariable String[] ids){

        for(String id:ids){
            orderService.deleteOrder(id);
        }
        return new ResultUtil<Object>().setData(null);
    }


    /**
     * 通过
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order/pass/{orderId}",method = RequestMethod.GET)
    public Result<Object> passOrder(@PathVariable String orderId){
        TbUser user = getCurrentUser();
        TbOrder order = orderService.getTbOrderById(orderId);
        TbOrganization organization = organizationService.getOrganizationById(user.getOrganizationId());
        if(organization.getBalance().compareTo(order.getPayBalance()) == -1){
            return new ResultUtil<Object>().setErrorMsg("部门余额不足");
        }
        orderService.approvalOrder(orderId,user.getRoleId(),1);
        return new ResultUtil<Object>().setData(null);
    }

    /**
     * 拒绝
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order/refuse/{orderId}",method = RequestMethod.GET)
    public Result<Object> refuseOrder(@PathVariable String orderId){

        orderService.approvalOrder(orderId,0,0);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/order/statisticStatus",method = RequestMethod.GET)
    public Result<Object> statisticOrderStatus(String startTime, String endTime){
        List<OrderChartData> orderChartDataList = orderService.statisticOrderStatus(startTime, endTime);
        Map<Integer, OrderChartData> map = orderChartDataList.stream().collect(Collectors.toMap(OrderChartData::getStatus, orderChartData -> orderChartData));
        for (int i = 0; i < 9; i++) {
            if(map.get(i) == null){
                OrderChartData orderChartData = new OrderChartData();
                orderChartData.setStatus(i);
                orderChartData.setNum(0);
                orderChartDataList.add(orderChartData);
            }
        }
        return new ResultUtil<Object>().setData(orderChartDataList);
    }

    @RequestMapping(value = "/order/statisticPayType",method = RequestMethod.GET)
    public Result<Object> statisticOrderPayType(String startTime, String endTime){
        List<OrderChartData> orderChartDataList = orderService.statisticOrderPayType(startTime, endTime);
        Map<Integer, OrderChartData> map = orderChartDataList.stream().collect(Collectors.toMap(OrderChartData::getPayType, orderChartData -> orderChartData));
        for (int i = 0; i < 2; i++) {
            if(map.get(i) == null){
                OrderChartData orderChartData = new OrderChartData();
                orderChartData.setPayType(i);
                orderChartData.setNum(0);
                orderChartDataList.add(orderChartData);
            }
        }
        return new ResultUtil<Object>().setData(orderChartDataList);
    }

    @RequestMapping(value = "/order/salesRanking",method = RequestMethod.GET)
    public DataTablesResult salesRanking(String startTime,String endTime){
        List<OrderRanking> orderRankingList = orderService.salesRanking(startTime, endTime);
        DataTablesResult result = new DataTablesResult();
        result.setData(orderRankingList);
        return result;
    }

    @RequestMapping(value = "/order/orgRanking",method = RequestMethod.GET)
    public DataTablesResult orgRanking(String startTime,String endTime){
        List<OrderRanking> orderRankingList = orderService.orgApplyRanking(startTime, endTime);
        DataTablesResult result = new DataTablesResult();
        result.setData(orderRankingList);
        return result;
    }

    @RequestMapping(value = "/order/salesStatistic",method = RequestMethod.GET)
    public DataTablesResult salesStatistic(String startTime,String endTime){
        List<OrderRanking> orderRankingList = orderService.salesStatistic(startTime, endTime);
        DataTablesResult result = new DataTablesResult();
        result.setData(orderRankingList);
        return result;
    }

    @RequestMapping(value = "/order/exportSalesStatistic",method = RequestMethod.GET)
    public void exportSalesStatistic(String startTime, String endTime, HttpServletResponse response){
        List<OrderRanking> orderRankingList = orderService.salesStatistic(startTime, endTime);
        String filename = "商品销量报表";
        String[] rowName = new String[]{"商品名称","销售数量(件)","销售金额(元)"};
        List<Object[]> dataList = new ArrayList<>();
        for(OrderRanking orderRanking : orderRankingList){
            Object[] data = new Object[]{orderRanking.getItemTitle(),orderRanking.getSaleNum(),orderRanking.getSaleAmount()};
            dataList.add(data);
        }
        writeExcel(rowName,dataList,filename,startTime,endTime,response);
    }

    private void writeExcel(String[] rowName,List<Object[]> dataList,String fileName,String startTime,String endTime,HttpServletResponse response){
        if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
            fileName += "(" + startTime+"至今)";
        }else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
            fileName += "(" + startTime + "~" + endTime+ ")";
        }else if (StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
            fileName += "(截止到" + endTime+ ")";
        }
        try {
            String fileNameIso = new String(fileName.getBytes(), "ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameIso+".xls");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream out = response.getOutputStream();
            ExportExcel exportExcel = new ExportExcel(fileName,rowName,dataList);
            exportExcel.export(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/order/orgApplyStatistic",method = RequestMethod.GET)
    public DataTablesResult orgApplyStatistic(String startTime,String endTime){
        List<OrderRanking> orderRankingList = orderService.orgApplyStatistic(startTime, endTime);
        DataTablesResult result = new DataTablesResult();
        result.setData(orderRankingList);
        return result;
    }

    @RequestMapping(value = "/order/exportOrgApplyStatistic",method = RequestMethod.GET)
    public void exportOrgApplyStatistic(String startTime, String endTime, HttpServletResponse response){
        List<OrderRanking> orderRankingList = orderService.orgApplyStatistic(startTime, endTime);
        String filename = "部门申领报表";
        String[] rowName = new String[]{"部门名称","申领商品数量(件)","申领总金额(元)"};
        List<Object[]> dataList = new ArrayList<>();
        for(OrderRanking orderRanking : orderRankingList){
            Object[] data = new Object[]{orderRanking.getOrganizationName(),orderRanking.getApplyNum(),orderRanking.getApplyAmount()};
            dataList.add(data);
        }
        writeExcel(rowName,dataList,filename,startTime,endTime,response);
    }


    @RequestMapping(value = "/order/userApplyStatistic",method = RequestMethod.GET)
    public DataTablesResult userApplyStatistic(String startTime,String endTime){
        List<OrderRanking> orderRankingList = orderService.userApplyStatistic(startTime, endTime);
        DataTablesResult result = new DataTablesResult();
        result.setData(orderRankingList);
        return result;
    }

    @RequestMapping(value = "/order/exportUserApplyStatistic",method = RequestMethod.GET)
    public void exportUserApplyStatistic(String startTime, String endTime, HttpServletResponse response){
        List<OrderRanking> orderRankingList = orderService.userApplyStatistic(startTime, endTime);
        String filename = "用户申领报表";
        String[] rowName = new String[]{"用户名","商品名称","申领商品数量(件)","申领总金额(元)"};
        List<Object[]> dataList = new ArrayList<>();
        for(OrderRanking orderRanking : orderRankingList){
            Object[] data = new Object[]{orderRanking.getUsername(),orderRanking.getItemTitle(),orderRanking.getApplyNum(),orderRanking.getApplyAmount()};
            dataList.add(data);
        }
        writeExcel(rowName,dataList,filename,startTime,endTime,response);
    }
}
